package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.UserLoginService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
@Service
@Transactional
public class UserLoginServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements UserLoginService {
    @Override
    public ResponseResult login(AdUserDto dto) {
        //1.检查参数
        if(StringUtils.isEmpty(dto.getName())||StringUtils.isEmpty(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户名或密码不能为空");
        }
        LambdaQueryWrapper<AdUser> wrapper = new LambdaQueryWrapper<>();//根据用户名查询用户
        wrapper.eq(AdUser::getName, dto.getName());
        List<AdUser> list = list(wrapper);
        if(ObjectUtils.isEmpty(list)){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
        AdUser adUser = list.get(0);
        String pw=dto.getPassword()+adUser.getSalt();
        String pwd = DigestUtils.md5DigestAsHex(pw.getBytes());
        if(!pwd.equals(list.get(0).getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);//密码错误
        }
        HashMap<String, Object> map = new HashMap<>();
        adUser.setPassword("");
        adUser.setSalt("");//由于密码和盐是需要保密的不予透露
        map.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
        map.put("user",adUser);
        return ResponseResult.okResult(map);
    }
}
